import Vue from 'vue'
import Vuex from 'vuex'
import utils from "../utils"

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: utils.getLocalStorage("token") || "",
    me: utils.getLocalStorage("me") || {},
    count: utils.getLocalStorage("account") || {},
    config: utils.getLocalStorage("config") || {},
  },
  getters: {
    isLogin(state){
      return !!(state.token && state.token.access_token)
    }
  },
  mutations: {
    handleToken(state, token) {
      state.token = token;
      utils.setLocalStorage("token", token);
    },
    handleLogout(state) {
      state.token = null;
      state.me = null;
      utils.removeLocalStorage("token");
      utils.removeLocalStorage("me");
    },
    handleConfig(state,payload) {
      state.config = payload;
      utils.setLocalStorage("config", payload);
    },
    handleMe(state, me) {
      state.me = me;
      utils.setLocalStorage("me", me);
    },
    handleAccount(state, payload) {
      if (payload.remenber) {
        state.count = payload;
        utils.setLocalStorage("account", payload)
      } else {
        state.count = {};
        utils.removeLocalStorage("account");
      }
    },
  },
  actions: {
    Login(context, payload) {
      return new Promise((resolve, reject) => {
        let api = Vue.prototype.$http.api.auth.login(
          payload.telephone, payload.password
        );
        Vue.prototype.$http.callApi(api).then(res => {
          context.commit("handleToken", res.data);
          context.dispatch("GetMe").then(resolve).catch(reject);
          resolve(res)
        }).catch(reject);
      })
    },
    GetMe(context, payload) {
      return new Promise((resolve, reject) => {
        let api = Vue.prototype.$http.api.member.getMe();
        Vue.prototype.$http.callApi(api).then(res => {
          context.commit("handleMe", res.data);
          resolve(res.data);
        }).catch(reject);
      })
    },
    GetConfig(context, payload) {
      return new Promise((resolve, reject) => {
        let api = Vue.prototype.$http.api.config.getAll();
        Vue.prototype.$http.callApi(api).then(res => {
          context.commit("handleConfig", res.data);
          resolve(res.data);
        }).catch(reject);
      })
    },
  },
  modules: {
  }
})
